package cn.com.taiji.oospub.wechat.common.wxpay.pay;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

/**
 * 去支付
 * @author fan
 *
 */
@Component
public class UnifiedorderService {

	@Value("${appID}")
	public String appID;
	@Value("${appsecret}")
	public String appsecret;
	//微信支付分配的商户号ID（开通公众号的微信支付功能之后可以获取到）
	@Value("${mchID}")
	public String mchID;
	@Value("${key}")
	public String key;
	@Autowired
	public Signature signature;
	protected static Logger logger = LoggerFactory.getLogger(UnifiedorderService.class);
      
    @SuppressWarnings("static-access")
	public  String postReturnXml(WxPaySendData data, HttpServletRequest request){
    	String postReturnXml = null;
		HttpClientUtil http;
		try {
			HashMap<String,Object> map = new HashMap<String,Object>(); 
			map.put("appid",appID);
			map.put("attach", data.getAttach());
			map.put("body", data.getBody());
			map.put("mch_id", mchID);
			map.put("openid", data.getOpenid());
			map.put("nonce_str", data.getNonceStr());
			map.put("out_trade_no", data.getOutTradeNo());
			map.put("total_fee", data.getTotalFee());
			String ip =  CommonTools.getIp(request);
			if ("0:0:0:0:0:0:0:1".equals(ip)) {
				ip = "127.0.0.1";
			}
//			map.put("spbill_create_ip", ip);
			map.put("spbill_create_ip", "127.0.0.1");
			System.out.println(ip);
//			String notify_url="http://crazymusic.com.cn/oosweb/weixin/notity";
			map.put("notify_url", data.getNotifyUrl());
			map.put("trade_type", Configure.TradeType_GZH);
			String sign = signature.getSign(map);
			logger.info("发送签名:" + sign);
			map.put("sign", sign);
			logger.info("发送mchID:" + mchID);
			logger.info("发送appid:" + appID);

//			sign = new String(sign.getBytes(),"UTF-8");
//			sign = URLEncoder.encode(sign, "UTF-8");
//			map.put("sign", new String(sign.getBytes("ISO-8859-1"),"gbk"));
			
			StringBuffer sb = new StringBuffer();  
			sb.append("<xml>");
			MainServlet.mapToXMLTest2(map, sb);  
			sb.append("</xml>");
			logger.info("请求的xml为:" + sb.toString());
			http = new HttpClientUtil();
			
//			postReturnXml =  http.sendPost(Configure.PAY_API ,sb.toString());
//			postReturnXml =  http.sendPost1(sb.toString() , Configure.PAY_API );
			System.out.println("postReturnXml-----------"+postReturnXml);
			System.out.println("postReturnXml-----------"+postReturnXml);
			System.out.println("postReturnXml-----------"+postReturnXml);
			System.out.println("postReturnXml-----------"+postReturnXml);

			postReturnXml = http.post(Configure.PAY_API, sb.toString());
			
			
			
//			(1)
//			HttpUtil send = new HttpUtil(Configure.PAY_API); 			
//			postReturnXml  = send.sendToBoss(new String (sb.toString().getBytes(), "s"));
			
//			new IPUtil().getRemoteAddress(request)); //终端IP
			
			logger.info("返回结果:" + postReturnXml);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return postReturnXml;
    }
    
    @SuppressWarnings("static-access")
	public static String jsapiSign(WxPaySendData data){
    	String postReturnXml = null;
		HttpClientUtil http =new HttpClientUtil(); 
		try {
			HashMap<String,String> map = new HashMap<String,String>(); 
			map.put("jsapi_ticket", data.getJsapiTicket());
			map.put("nonceStr", data.getNonceStr());
			map.put("timestamp", data.getTimeStamp());
			map.put("url", data.getJspUrl());
			String sign = Signature.formatUrlMap(map, true, true);
			postReturnXml = sign;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return postReturnXml;
    }
    
    
    
	public static String getSha1(String str){
	    if (null == str || 0 == str.length()){
	        return null;
	    }
	    char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
	            'a', 'b', 'c', 'd', 'e', 'f'};
	    try {
	        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
	        mdTemp.update(str.getBytes("UTF-8"));
	         
	        byte[] md = mdTemp.digest();
	        int j = md.length;
	        char[] buf = new char[j * 2];
	        int k = 0;
	        for (int i = 0; i < j; i++) {
	            byte byte0 = md[i];
	            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
	            buf[k++] = hexDigits[byte0 & 0xf];
	        }
	        return new String(buf);
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	    }
	    
	    return "";
	}
	
	
	
}
